import { getToken } from '@/utils/auth';
import router from './router';
import store from './store';
import jwtDecode from 'jwt-decode';

// 白名单
const whiteList = [
  '/login',
  '/useragree',
  '/privacypolicy',
  '/home',
  '/news',
  '/news/detail',
  '/college/searchCollege',
  '/college/detail',
  '/college/admissionsguide',
  '/majorLibrary',
  '/majorLibrary/majorLibraryDet',
  '/jorLibrary',
  '/jorLibrary/jorLibraryDet/jorDet',
  '/jorLibrary/jorLibraryDet',
  '/shopserve',
  '/experts',
  '/college/collegeimgs',
  '/college/admissionsguide/det',
  '/shopserve/shopDet',
  '/homesearch',
  '/appraisal',
];
router.beforeEach((to, _, next) => {
  // 动态设置标题
  if (to.meta.title) {
    document.title = process.env.VUE_APP_TITLE;
  } else {
    document.title = process.env.VUE_APP_TITLE; //此处写默认的title
  }
  if (getToken()) {
    //从token里面解密出来用户信息
    let userInfo = jwtDecode(getToken());
    const chance_last_time = userInfo.data.chance_last_time;
    const startDate = `${chance_last_time.slice(0, 4)}-06-20`; // 起始日期 20250620
    const endDate = `${chance_last_time.slice(0, 4)}-09-01`; // 结束日期 20250901
    // 使用字符串截取并格式化为 'YYYY-MM-DD' 格式
    const checkDate = `${chance_last_time.slice(0, 4)}-${chance_last_time.slice(4, 6)}-${chance_last_time.slice(6)}`;
    if (
      userInfo.data.isVIP == 3 &&
      checkDate >= startDate &&
      checkDate <= endDate
    ) {
      userInfo.data.isVIP = 0;
    }

    store.dispatch('user/changeUserInfo', userInfo.data); //将用户信息存储到vuex中
    if (to.path === '/login') {
      next('/home'); // 重定向到"/home"页面
    } else {
      next(); // 允许用户继续访问其他页面
    }
  } else {
    // 用户未登录，重定向到登录页面（除非在白名单中）
    if (whiteList.includes(to.path)) {
      next(); // 在白名单中，允许用户继续访问
    } else {
      next('/login'); // 如果不在白名单中，则跳转到登录页面
    }
  }
});
